package com.autoagent.ai_live_master.scriptRecommendation.service.impl;

import com.autoagent.ai_live_master.common.utils.BeanConverter;
import com.autoagent.ai_live_master.scriptRecommendation.dto.ForbiddenTermsDTO;
import com.autoagent.ai_live_master.scriptRecommendation.entity.ForbiddenTerms;
import com.autoagent.ai_live_master.scriptRecommendation.mapper.ForbiddenTermsMapper;
import com.autoagent.ai_live_master.scriptRecommendation.service.ForbiddenTermsService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 违禁词库服务实现类
 */
@Slf4j
@Service
public class ForbiddenTermsServiceImpl extends ServiceImpl<ForbiddenTermsMapper, ForbiddenTerms> implements ForbiddenTermsService {

    @Override
    public ForbiddenTermsDTO getForbiddenTermsById(Integer id) {
        log.info("开始获取违禁词 - id: {}", id);
        try {
            ForbiddenTerms forbiddenTerms = this.getById(id);
            if (forbiddenTerms == null) {
                log.warn("违禁词不存在 - id: {}", id);
                return null;
            }
            log.info("获取违禁词成功 - id: {}", id);
            return BeanConverter.convert(forbiddenTerms, ForbiddenTermsDTO.class);
        } catch (Exception e) {
            log.error("获取违禁词失败 - id: {}, 错误信息: {}", id, e.getMessage(), e);
            throw e;
        }
    }

    @Override
    public List<ForbiddenTermsDTO> getAllForbiddenTerms(Long userId) {
        log.info("开始获取用户违禁词列表 - userId: {}", userId);
        try {
            // 构造查询条件：user_id = userId
            LambdaQueryWrapper<ForbiddenTerms> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ForbiddenTerms::getUserId, userId);

            List<ForbiddenTerms> forbiddenTermsList = this.list(queryWrapper);
            log.info("获取用户违禁词列表成功 - userId: {}, 数量: {}", userId, forbiddenTermsList.size());

            return forbiddenTermsList.stream()
                    .map(forbiddenTerms -> BeanConverter.convert(forbiddenTerms, ForbiddenTermsDTO.class))
                    .collect(Collectors.toList());
        } catch (Exception e) {
            log.error("获取用户违禁词列表失败 - userId: {}, 错误信息: {}", userId, e.getMessage(), e);
            throw e;
        }
    }

    @Override
    public Page<ForbiddenTermsDTO> getPageByUserId(Long userId, Integer pageNum, Integer pageSize, String keyword) {
        log.info("分页获取用户的违禁词库列表 - 用户ID: {}, 页码: {}, 每页大小: {}, 关键字: {}", userId, pageNum, pageSize, keyword);

        Page<ForbiddenTerms> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<ForbiddenTerms> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ForbiddenTerms::getUserId, userId);

        // 如果有关键字，添加termName字段的模糊匹配
        if (keyword != null && !keyword.trim().isEmpty()) {
            wrapper.like(ForbiddenTerms::getTermName, keyword.trim());
        }

        // 按创建时间倒序排列
        wrapper.orderByDesc(ForbiddenTerms::getCreatedAt);

        Page<ForbiddenTerms> entityPage = this.page(page, wrapper);

        // 转换为DTO分页对象
        Page<ForbiddenTermsDTO> dtoPage = new Page<>();
        dtoPage.setTotal(entityPage.getTotal());
        dtoPage.setCurrent(entityPage.getCurrent());
        dtoPage.setSize(entityPage.getSize());
        dtoPage.setRecords(entityPage.getRecords().stream()
                .map(entity -> BeanConverter.convert(entity, ForbiddenTermsDTO.class))
                .collect(Collectors.toList()));

        return dtoPage;
    }

    @Override
    public void createForbiddenTerms(ForbiddenTerms forbiddenTerms) {
        log.info("开始创建违禁词 - 内容: {}", forbiddenTerms);
        try {
            // 保存新违禁词库
            boolean success = this.save(forbiddenTerms);
            if (success) {
                log.info("创建违禁词成功 - id: {}", forbiddenTerms.getId());
            } else {
                log.warn("创建违禁词失败");
                throw new RuntimeException("创建违禁词失败");
            }
        } catch (Exception e) {
            log.error("创建违禁词失败 - 错误信息: {}", e.getMessage(), e);
            throw e;
        }
    }

    @Override
    public ForbiddenTermsDTO updateForbiddenTerms(ForbiddenTerms forbiddenTerms) {
        log.info("开始更新违禁词 - id: {}, 更新内容: {}", forbiddenTerms.getId(), forbiddenTerms);
        try {
            // 检查违禁词库是否存在
            ForbiddenTerms existingForbiddenTerms = this.getById(forbiddenTerms.getId());
            if (existingForbiddenTerms == null) {
                log.warn("更新失败 - 违禁词不存在, id: {}", forbiddenTerms.getId());
                return null;
            }
            // 违禁词库存在，执行更新
            boolean success = this.updateById(forbiddenTerms);
            if (!success) {
                log.warn("更新违禁词失败 - id: {}", forbiddenTerms.getId());
                throw new RuntimeException("更新违禁词失败");
            }
            log.info("更新违禁词成功 - id: {}", forbiddenTerms.getId());
            // 重新获取更新后的违禁词库信息
            return getForbiddenTermsById(forbiddenTerms.getId());
        } catch (Exception e) {
            log.error("更新违禁词失败 - id: {}, 错误信息: {}", forbiddenTerms.getId(), e.getMessage(), e);
            throw e;
        }
    }

    @Override
    public boolean deleteForbiddenTerms(Integer id) {
        log.info("开始删除违禁词 - id: {}", id);
        try {
            // 检查违禁词库是否存在
            ForbiddenTerms existingForbiddenTerms = this.getById(id);
            if (existingForbiddenTerms == null) {
                log.warn("删除失败 - 违禁词不存在, id: {}", id);
                return false;
            }
            // 违禁词库存在，执行删除
            boolean success = this.removeById(id);
            if (success) {
                log.info("删除违禁词成功 - id: {}", id);
            } else {
                log.warn("删除违禁词失败 - id: {}", id);
            }
            return success;
        } catch (Exception e) {
            log.error("删除违禁词失败 - id: {}, 错误信息: {}", id, e.getMessage(), e);
            throw e;
        }
    }
}